package org.pr.logoupdate.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
//import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.log4j.Logger;
import org.pr.logoupdate.util.Constant;
import org.pr.logoupdate.util.StringUtil;

/**
 * Servlet implementation class LogoUploaderServlet
 */
@WebServlet("/servlet/logoUpload")
@MultipartConfig
public class LogoUploaderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Logger logger = Logger.getLogger(LogoUploaderServlet.class);
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LogoUploaderServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
//		response.getWriter().append("Served at: ").append(request.getContextPath());
//		PrintWriter out = response.getWriter();
		//打印出类名，主要是为了看一下，这个request的具体实现类是哪个
//		System.out.println(request.getClass().getName());
		logger.debug(request.getClass().getName());
//		out.println(request.getClass().getName());
//		System.out.println(request.getContentType());
		logger.debug(request.getContentType());
//		out.println(request.getContentType());
		boolean hasError = false;
		String error = "";
		String contentType = request.getContentType();
		if(contentType != null && contentType.contains("multipart/form-data")) {
			Part part = request.getPart("logo");//这个参数值，就是jsp里面input控件的name
			if(part == null) {
//				out.println("no file as name of upload input");
				hasError = true;
				error = "是不是忘记上传头像了，再试试";
				logger.error(error);
			} else {
				String original = part.getSubmittedFileName();
				if(original == null || original.isEmpty()) {
//					out.println("looks that there is no filename and content");
					hasError = true;
					error = "是不是忘记上传头像了，再试试";
					logger.error(error);
				} else {
					String filename = original.toLowerCase();
					if (!filename.endsWith(".jpg")
							&& !filename.endsWith(".jpeg")
							&& !filename.endsWith(".bmp")
							&& !filename.endsWith(".png")
							&& !filename.endsWith(".gif")) {
						hasError = true;
						error = "对不起，我们暂时仅支持jpg，bmp，png，gif格式的图片";
					} else {
						String tempFolder = System.getProperty("java.io.tmpdir");
						String sessionId = request.getSession().getId();
						String fileSuffix = StringUtil.getFileSuffix(original);
						//获取临时文件夹
						File newFileFolder = new File(tempFolder, sessionId);
						newFileFolder.mkdirs();
						File newFile = new File(newFileFolder.getAbsolutePath(), sessionId + fileSuffix);
						InputStream is = part.getInputStream();
						FileOutputStream fos = new FileOutputStream(newFile);
						byte [] content = new byte[1024];
						int num;
						while((num = is.read(content)) != -1) {
							fos.write(content, 0, num);
						}
//						int length = is.available();
//						byte [] content = new byte[length];
//						is.read(content);
						is.close();
//						fos.write(content);
						fos.close();
//						System.out.println("file upload to this folder " + newFile.getAbsolutePath());
						logger.debug("file upload to this folder " + newFile.getAbsolutePath());
						request.getSession().setAttribute(Constant.UPLOAD_FILENAME, newFile.getName());
//						out.println("file upload to this folder " + newFile.getAbsolutePath());
					}
				}
			}
		} else {
//			out.println("not a file upload request");
			hasError = true;
			error = "不是一个正常的文件上传请求";
		}
		if (hasError) {
			request.getSession().setAttribute(Constant.PAGE1_ERROR, error);
			response.sendRedirect(request.getContextPath() + "/index.jsp");
		} else {
			response.sendRedirect(request.getContextPath() + "/step2.jsp");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
